package xinyu.customer.news;

import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.logos.common.source.network.entity.BaseNetEntity;
import com.netease.nim.uikit.business.recent.RecentContactsCallback;
import com.netease.nim.uikit.business.recent.RecentContactsFragment;
import com.netease.nim.uikit.common.ToastHelper;
import com.netease.nimlib.sdk.NIMClient;
import com.netease.nimlib.sdk.Observer;
import com.netease.nimlib.sdk.StatusCode;
import com.netease.nimlib.sdk.auth.AuthServiceObserver;
import com.netease.nimlib.sdk.msg.MsgService;
import com.netease.nimlib.sdk.msg.attachment.MsgAttachment;
import com.netease.nimlib.sdk.msg.model.IMMessage;
import com.netease.nimlib.sdk.msg.model.RecentContact;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import xinyu.customer.R;
import xinyu.customer.adapter.NewsMainTopAdapter;
import xinyu.customer.base.AppBaseActivity;
import xinyu.customer.base.AppBaseFragment;
import xinyu.customer.bean.NewsMainNetTopBean;
import xinyu.customer.bean.NewsMainTopBean;
import xinyu.customer.chat.extension.StickerAttachment;
import xinyu.customer.chat.reminder.ReminderManager;
import xinyu.customer.chat.session.SessionHelper;
import xinyu.customer.login.LoginActivity;
import xinyu.customer.login.LogoutHelper;
import xinyu.customer.news.data.NewsTabMainContract;
import xinyu.customer.news.data.NewsTabMainPresenter;
import xinyu.customer.news.data.NewsTabMainRemoteDataSource;
import xinyu.customer.util.Preferences;
import xinyu.customer.util.SpConstant;

/**
 * description ： TODO:类的作用
 * author : SIGHT-WXC
 * email : 391335693@qq.com
 * date : 2020-04-15 15:22
 */
public class NewsTabMainFragment extends AppBaseFragment implements NewsTabMainContract.View{

    private RecyclerView rvTop;

    private String TAG = NewsTabMainFragment.class.getSimpleName();
    private RecentContactsFragment fragment;
    private LinearLayout notifyBar;
    private TextView notifyBarText;

    private NewsTabMainContract.Presenter mPresenter;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = View.inflate(getContext(), R.layout.fragment_news_tab_main, null);
        initView(view);

        registerObservers(true);
        addRecentContactsFragment();
        return view;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getData();
    }

    private void addRecentContactsFragment() {
        fragment = new RecentContactsFragment();
        fragment.setContainerId(R.id.messages_fragment);

        final AppBaseActivity activity = (AppBaseActivity) getActivity();
        fragment = (RecentContactsFragment) activity.addFragment(fragment);
        fragment.setCallback(new RecentContactsCallback() {
            @Override
            public void onRecentContactsLoaded() {
                // 最近联系人列表加载完毕
            }
            @Override
            public void onUnreadCountChange(int unreadCount) {
                ReminderManager.getInstance().updateSessionUnreadNum(unreadCount);
            }

            @Override
            public void onItemClick(RecentContact recent) {
                // 回调函数，以供打开会话窗口时传入定制化参数，或者做其他动作
                switch (recent.getSessionType()) {
                    case P2P:
                        SessionHelper.startP2PSession(getActivity(), recent.getContactId());
                        break;
                    case Team:
                        SessionHelper.startTeamSession(getActivity(), recent.getContactId());
                        break;
                }
            }

            @Override
            public String getDigestOfAttachment(RecentContact recentContact, MsgAttachment attachment) {
                // 设置自定义消息的摘要消息，展示在最近联系人列表的消息缩略栏上
                // 当然，你也可以自定义一些内建消息的缩略语，例如图片，语音，音视频会话等，自定义的缩略语会被优先使用。
                if (attachment instanceof StickerAttachment) {
                    return "[表情消息]";
                }
                return null;
            }

            @Override
            public String getDigestOfTipMsg(RecentContact recent) {
                String msgId = recent.getRecentMessageId();
                List<String> uuids = new ArrayList<>(1);
                uuids.add(msgId);
                List<IMMessage> msgs = NIMClient.getService(MsgService.class).queryMessageListByUuidBlock(uuids);
                if (msgs != null && !msgs.isEmpty()) {
                    IMMessage msg = msgs.get(0);
                    Map<String, Object> content = msg.getRemoteExtension();
                    if (content != null && !content.isEmpty()) {
                        return (String) content.get("content");
                    }
                }

                return null;
            }
        });
    }

    /**
     * 初始化presenter
     */
    private void getData() {
        mPresenter = new NewsTabMainPresenter(this,new NewsTabMainRemoteDataSource());
        mPresenter.getNewsTopMain(SpConstant.getUserId());
    }

    private void initView(View view) {
        rvTop = view.findViewById(R.id.rv_top);

        notifyBar = view.findViewById(R.id.status_notify_bar);
        notifyBarText = view.findViewById(R.id.status_desc_label);
        notifyBar.setVisibility(View.GONE);
    }
    /**
     * ********************** 收消息，处理状态变化 ************************
     */
    private void registerObservers(boolean register) {
        NIMClient.getService(AuthServiceObserver.class).observeOnlineStatus(userStatusObserver, register);

    }


    /**
     * 用户状态变化
     */
    Observer<StatusCode> userStatusObserver = new Observer<StatusCode>() {
        @Override
        public void onEvent(StatusCode code) {
            if (code.wontAutoLogin()) {
                kickOut(code);
            } else {
                if (code == StatusCode.NET_BROKEN) {
                    notifyBar.setVisibility(View.VISIBLE);
                    notifyBarText.setText(R.string.net_broken);
                } else if (code == StatusCode.UNLOGIN) {
                    notifyBar.setVisibility(View.VISIBLE);
                    notifyBarText.setText(R.string.nim_status_unlogin);
                } else if (code == StatusCode.CONNECTING) {
                    notifyBar.setVisibility(View.VISIBLE);
                    notifyBarText.setText(R.string.nim_status_connecting);
                } else if (code == StatusCode.LOGINING) {
                    notifyBar.setVisibility(View.VISIBLE);
                    notifyBarText.setText(R.string.nim_status_logining);
                } else {
                    notifyBar.setVisibility(View.GONE);
                }
            }
        }
    };



    private void kickOut(StatusCode code) {
        Preferences.saveUserToken("");
        if (code == StatusCode.PWD_ERROR) {
            ToastHelper.showToast(getActivity(), R.string.login_failed);
        }
        onLogout();
    }

    // 注销
    private void onLogout() {
        // 清理缓存&注销监听&清除状态
        LogoutHelper.logout();
        startActivity(new Intent(getActivity(),LoginActivity.class));
        getActivity().finish();
    }

    @Override
    public void setPresenter(NewsTabMainContract.Presenter presenter) {
            mPresenter = presenter;
    }

    @Override
    public void showLoading() {

    }

    @Override
    public void hideLoading() {

    }

    @Override
    public void showMessage(String message) {

    }

    @Override
    public void onNewsTabMainTopSuccess(BaseNetEntity<NewsMainNetTopBean> newsMainTopBeanBaseNetEntity) {
        List<NewsMainTopBean> newsMainTopBeanList = new ArrayList<>();
        NewsMainNetTopBean result = newsMainTopBeanBaseNetEntity.getResult();
        for (int i = 0; i < 4; i++) {
            NewsMainTopBean newsMainTopBean = new NewsMainTopBean();
            switch (i){
                case 0:
                    newsMainTopBean.setNum(result.getForumUnreadNums());
                    newsMainTopBean.setName("互动通知");
                    newsMainTopBean.setImgUrlId(R.mipmap.img_interactive_notification);
                    break;
                case 1:
                    newsMainTopBean.setNum(result.getSystemUnreadNums());
                    newsMainTopBean.setName("系统通知");
                    newsMainTopBean.setImgUrlId(R.mipmap.img_systematic_notification);
                    break;
                case 2:
                    newsMainTopBean.setNum(result.getVideoVoiceUnreadNums());
                    newsMainTopBean.setName("视频语音");
                    newsMainTopBean.setImgUrlId(R.mipmap.img_audio_video);
                    break;
                case 3:
                    newsMainTopBean.setNum(result.getGroupUnreadNums());
                    newsMainTopBean.setName("群助手");
                    newsMainTopBean.setImgUrlId(R.mipmap.img_helper);
                    break;
            }
            newsMainTopBeanList.add(newsMainTopBean);
        }
        NewsMainTopAdapter adapter = new NewsMainTopAdapter(getContext());
        adapter.resetItem(newsMainTopBeanList);
        rvTop.setAdapter(adapter);
        rvTop.setLayoutManager(new GridLayoutManager(getContext(),4));
    }
}
